package c.m.d.b.service.impl;

import c.m.d.b.beans.EntityType;
import c.m.d.b.dao.EntityTypeRepository;
import c.m.d.b.exception.CMDBException;
import c.m.d.b.service.EntityTypeService;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Service(value = "entityTypeService")
public final class EntityTypeServiceImpl implements EntityTypeService
{
    @Autowired
    private EntityTypeRepository entityTypeRepository;

    @Transactional
    @Override
    public String createEntityType(@NotNull EntityType entityType)
    {
        EntityType savedEntityType = entityTypeRepository.save(entityType);
        return savedEntityType.getEntityTypeName();
    }

    @Transactional(readOnly = true)
    @Override
    public EntityType getEntityType(@NotEmpty String entityTypeName)
    {
        EntityType entityType = entityTypeRepository.findOne(entityTypeName);
        if (entityType == null)
        {
            throw new CMDBException(CMDBException.CMDBErrorCode.NOT_FOUND);
        }
        return entityType;
    }

    @Transactional(readOnly = true)
    @Override
    public List<String> getEntityTypesNames()
    {
        List<EntityType> entityTypes = entityTypeRepository.findAll();
        List<String> entityTypeNames = new ArrayList<String>();
        for(EntityType entityType:entityTypes){
            entityTypeNames.add(entityType.getEntityTypeName());
        }
        return entityTypeNames;
    }
}
